import hashlib
import hmac
import time

from django.conf import settings


def generate_reset_token(user, request=None):
    """生成带客户端信息的重置令牌"""
    # 获取客户端信息（如有请求对象）
    client_ip = request.META.get('REMOTE_ADDR', '') if request else ''
    user_agent = request.META.get('HTTP_USER_AGENT', '')[:50] if request else ''

    # 生成令牌（示例使用HMAC-SHA256）
    timestamp = int(time.time())
    payload = f"{user.id}|{timestamp}|{client_ip}|{user_agent}"
    signature = hmac.new(
        key=settings.SECRET_KEY.encode(),
        msg=payload.encode(),
        digestmod=hashlib.sha256
    ).hexdigest()
    return f"{payload}:{signature}"
